<?php
/**
 * Created by PhpStorm.
 * User: 风哀伤
 * Date: 2019/12/20
 * Time: 16:54
 * @copyright: (c)2019 人人禾匠商城
 * @link: http://bbs.52jscn.com
 */

namespace app\plugins\wxapp\forms\subscribe;


use app\core\response\ApiCode;
use app\models\Model;
use app\plugins\wxapp\models\WxappSubscribe;
use app\plugins\wxapp\Plugin;

/**
 * Class SubscribeForm
 * @package app\plugins\wxapp\forms\subscribe
 * @property Plugin $plugin
 */
class SubscribeForm extends Model
{
    protected $plugin;
    public $mall;

    public function init()
    {
        parent::init(); // TODO: Change the autogenerated stub
        $this->plugin = new Plugin();
    }

    /**
     * @param $templateList
     * @return array
     * @throws \Exception
     * 微信小程序后台添加模板消息
     */
    public function addTemplate($templateList)
    {
        try {
            $wechatTemplate = $this->plugin->getSubscribe();
            $list = $wechatTemplate->getTemplateList();
            $newList = $list['data'];
            $templateIdList = [];
            foreach ($templateList as $index => $item) {
                $flag = true;
                foreach ($newList as $value) {
                    if (trim($item['title']) == trim($value['title'])) {
                        $templateIdList[] = [
                            'tpl_name' => $index,
                            'tpl_id' => $value['priTmplId']
                        ];
                        $flag = false;
                        break;
                    }
                }
                if ($flag) {
                    try {
                        $res = $wechatTemplate->addTemplate($item['id'], $item['keyword_id_list'], '添加订阅模板');
                        $templateIdList[] = [
                            'tpl_name' => $index,
                            'tpl_id' => $res['priTmplId']
                        ];
                    } catch (\Exception $exception) {
                        continue;
                    }
                }
            }
            return $templateIdList;
        } catch (\Exception $exception) {
            throw $exception;
        }
    }

    /**
     * @return array
     * 类目307--服装/鞋/箱包 774--广告/设计 订阅消息配置
     */
    public function getTemplateInfo()
    {
        return [
            'order_pay_tpl' => [
                'id' => '434',
                'keyword_id_list' => [6, 5, 9, 1],
                'title' => '下单成功提醒',
                'categoryId' => '307', // 类目id
                'type' => 2, // 订阅类型 2--一次性订阅 1--永久订阅
                'data' => [
                    'character_string6' => '',
                    'date5' => '',
                    'amount9' => '',
                    'thing1' => '',
                ]
            ],
            'order_cancel_tpl' => [
                'id' => '994',
                'keyword_id_list' => [8, 1, 4, 7],
                'title' => '订单取消通知',
                'categoryId' => '307', // 类目id
                'type' => 2, // 订阅类型 2--一次性订阅 1--永久订阅
                'data' => [
                    'name8' => '',
                    'character_string1' => '',
                    'amount4' => '',
                    'thing7' => '',
                ]
            ],
            'order_send_tpl' => [
                'id' => '855',
                'keyword_id_list' => [2, 7, 4, 8],
                'title' => '订单发货通知',
                'categoryId' => '307', // 类目id
                'type' => 2, // 订阅类型 2--一次性订阅 1--永久订阅
                'data' => [
                    'thing2' => '',
                    'thing7' => '',
                    'character_string4' => '',
                    'thing8' => '',
                ]
            ],
            'order_refund_tpl' => [
                'id' => '1435',
                'keyword_id_list' => [4, 5, 2, 1],
                'title' => '退款通知',
                'categoryId' => '307', // 类目id
                'type' => 2, // 订阅类型 2--一次性订阅 1--永久订阅
                'data' => [
                    'character_string4' => '',
                    'thing5' => '',
                    'amount2' => '',
                    'thing1' => '',
                ]
            ],
            'enroll_success_tpl' => [
                'id' => '1437',
                'keyword_id_list' => [1, 2, 4],
                'title' => '活动状态通知',
                'categoryId' => '307', // 类目id
                'type' => 2, // 订阅类型 2--一次性订阅 1--永久订阅
                'data' => [
                    'thing1' => '',
                    'thing2' => '',
                    'thing4' => '',
                ]
            ],
            'audit_result_tpl' => [
                'id' => '818',
                'keyword_id_list' => [4, 2, 1, 3],
                'title' => '审核结果通知',
                'categoryId' => '307', // 类目id
                'type' => 2, // 订阅类型 2--一次性订阅 1--永久订阅
                'data' => [
                    'thing4' => '',
                    'phrase2' => '',
                    'thing1' => '',
                    'time3' => '',
                ]
            ],
            'withdraw_success_tpl' => [
                'id' => '2001',
                'keyword_id_list' => [1, 2, 3, 4],
                'title' => '提现成功通知',
                'categoryId' => '307', // 类目id
                'type' => 2, // 订阅类型 2--一次性订阅 1--永久订阅
                'data' => [
                    'amount1' => '',
                    'amount2' => '',
                    'thing3' => '',
                    'thing4' => '',
                ]
            ],
            'withdraw_error_tpl' => [
                'id' => '3173',
                'keyword_id_list' => [1, 2],
                'title' => '提现失败通知',
                'categoryId' => '307', // 类目id
                'type' => 2, // 订阅类型 2--一次性订阅 1--永久订阅
                'data' => [
                    'amount1' => '',
                    'name2' => '',
                ]
            ],
        ];
    }

    public function getDefault()
    {
        $iconUrlPrefix = \Yii::$app->request->hostInfo . \Yii::$app->request->baseUrl .
            '/statics/img/mall/tplmsg/wxapp/';
        return [
            [
                'name' => '商城模板消息',
                'key' => 'store',
                'list' => [
                    [
                        'name' => '下单成功提醒(类目: 服装/鞋/箱包 )',
                        'order_pay_tpl' => '',
                        'tpl_name' => 'order_pay_tpl',
                        'img_url' => $iconUrlPrefix . 'order_pay_tpl.png'
                    ],
                    [
                        'name' => '订单取消通知(类目: 服装/鞋/箱包 )',
                        'order_cancel_tpl' => '',
                        'tpl_name' => 'order_cancel_tpl',
                        'img_url' => $iconUrlPrefix . 'order_cancel_tpl.png'
                    ],
                    [
                        'name' => '订单发货通知(类目: 服装/鞋/箱包 )',
                        'order_send_tpl' => '',
                        'tpl_name' => 'order_send_tpl',
                        'img_url' => $iconUrlPrefix . 'order_send_tpl.png'
                    ],
                    [
                        'name' => '退款通知(类目: 服装/鞋/箱包 )',
                        'order_refund_tpl' => '',
                        'tpl_name' => 'order_refund_tpl',
                        'img_url' => $iconUrlPrefix . 'order_refund_tpl.png'
                    ],
                    [
                        'name' => '活动状态通知(类目: 服装/鞋/箱包 )',
                        'enroll_success_tpl' => '',
                        'tpl_name' => 'enroll_success_tpl',
                        'img_url' => $iconUrlPrefix . 'enroll_success_tpl.png'
                    ],
                    [
                        'name' => '审核结果通知(类目: 服装/鞋/箱包 )',
                        'audit_result_tpl' => '',
                        'tpl_name' => 'audit_result_tpl',
                        'img_url' => $iconUrlPrefix . 'mch-tpl-1.png'
                    ],
                ]
            ],
            [
                'name' => '分销模板消息',
                'key' => 'share',
                'list' => [
                    [
                        'name' => '提现成功通知(类目: 服装/鞋/箱包 )',
                        'withdraw_success_tpl' => '',
                        'tpl_name' => 'withdraw_success_tpl',
                        'img_url' => $iconUrlPrefix . 'withdraw_success_tpl.png'
                    ],
                    [
                        'name' => '提现失败通知(类目: 服装/鞋/箱包 )',
                        'withdraw_error_tpl' => '',
                        'tpl_name' => 'withdraw_error_tpl',
                        'img_url' => $iconUrlPrefix . 'withdraw_error_tpl.png'
                    ],
                ]
            ],
        ];
    }

    /**
     * @param $list
     * @return array
     * 重新调整数据结构
     */
    public function getList($list)
    {
        $default = $this->getDefault();

        if (!$list) {
            return $default;
        }

        $newList = [];
        foreach ($list as $item) {
            $newList[$item['tpl_name']] = $item['tpl_id'];
        }

        foreach ($default as $k => $item) {
            foreach ($item['list'] as $k2 => $item2) {
                if (isset($newList[$item2['tpl_name']])) {
                    $default[$k]['list'][$k2][$item2['tpl_name']] = $newList[$item2['tpl_name']];
                }
            }
        }

        return $default;
    }

    /**
     * @return array
     * 后台获取订阅消息列表
     */
    public function getDetail()
    {
        $list = $this->getTemplateList();
        return [
            'code' => ApiCode::CODE_SUCCESS,
            'msg' => '请求成功',
            'data' => [
                'list' => $this->getList($list)
            ]
        ];
    }

    /**
     * @return array
     * 一键获取订阅消息
     */
    public function saveAll()
    {
        try {
            $templateList = $this->getTemplateInfo();
            $templateIdList = $this->addTemplate($templateList);

            return [
                'code' => ApiCode::CODE_SUCCESS,
                'msg' => '',
                'data' => [
                    'list' => $this->getList($templateIdList),
                ]
            ];
        } catch (\Exception $exception) {
            return [
                'code' => ApiCode::CODE_ERROR,
                'msg' => $exception->getMessage()
            ];
        }
    }

    /**
     * @param $templateTpl
     * @return string
     * @throws \Exception
     * 获取单个订阅消息template_id
     */
    public function addTemplateOne($templateTpl)
    {
        $list = $this->getTemplateInfo();
        if (isset($list[$templateTpl])) {
            $params = $list[$templateTpl];
        } else {
            throw new \Exception('错误的模板消息参数');
        }
        $templateList = $this->addTemplate([$params]);
        if (empty($templateList)) {
            throw new \Exception('获取模板出错');
        }
        return $templateList[0]['tpl_id'];
    }

    /**
     * @param string $param
     * @return array
     * 获取所有的订阅消息
     */
    public function getTemplateList($param = '*')
    {
        $list = WxappSubscribe::find()->where(['mall_id' => \Yii::$app->mall->id])->select($param)->all();
        return $list;
    }

    /**
     * @param $attributes
     * @return bool
     * @throws \Exception
     * 保存订阅消息到数据库
     */
    public function addTemplateList($attributes)
    {
        foreach ($attributes as $item) {
            if (!isset($item['tpl_name'])) {
                throw new \Exception('缺少必要的参数tpl_name');
            }
            if (!isset($item[$item['tpl_name']])) {
                throw new \Exception("缺少必要的参数{$item['tpl_name']}");
            }
            $tpl = WxappSubscribe::findOne(['mall_id' => \Yii::$app->mall->id, 'tpl_name' => $item['tpl_name']]);
            $tplId = $item[$item['tpl_name']];
            if (!$tpl) {
                $tpl = new WxappSubscribe();
                $tpl->mall_id = \Yii::$app->mall->id;
                $tpl->tpl_name = $item['tpl_name'];
            }
            if ($tpl->tpl_id != $tplId) {
                $tpl->tpl_id = $tplId;
                if (!$tpl->save()) {
                    throw new \Exception((new Model())->getErrorMsg($tpl));
                } else {
                    continue;
                }
            } else {
                continue;
            }
        }
        return true;
    }

    public $data;
    public function save()
    {
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            if (!$this->data || !is_array($this->data)) {
                throw new \Exception('数据异常');
            }
            $newData = [];
            foreach ($this->data as $item) {
                foreach ($item['list'] as $item2) {
                    if (!isset($item2[$item2['tpl_name']])) {
                        throw new \Exception('默认数据有误、请排查<' . $item2['name'] . '>字段信息');
                    }
                    $newData[] = [
                        'tpl_name' => $item2['tpl_name'],
                        $item2['tpl_name'] => $item2[$item2['tpl_name']]
                    ];
                }
            }
            $this->addTemplateList($newData);

            $transaction->commit();
            return [
                'code' => ApiCode::CODE_SUCCESS,
                'msg' => '保存成功',
            ];
        } catch (\Exception $e) {
            $transaction->rollBack();
            return [
                'code' => ApiCode::CODE_ERROR,
                'msg' => $e->getMessage(),
            ];
        }
    }
}
